package com.syqc.comlib.base

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewbinding.ViewBinding
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider
import com.syqc.comlib.R
import com.syqc.comlib.appstate.AppStatus
import com.syqc.comlib.appstate.AppStatusManger
import com.syqc.comlib.custom.MLoadingDialog
import com.syqc.comlib.custom.MessageDialog
import com.syqc.comlib.entity.ToastEntity
import com.syqc.comlib.network.NetChangerReceiver
import com.syqc.comlib.network.NetUtil
import com.syqc.comlib.network.OnNetChangerListener
import com.syqc.comlib.rx.LiveDataBus
import com.syqc.comlib.utils.AppManager
import com.syqc.comlib.utils.BuildConfigs
import com.syqc.comlib.utils.Language
import com.syqc.comlib.utils.toast
import com.syqc.comlib.utils.zClass
import kotlin.system.exitProcess

abstract class BaseActivity<VB : ViewBinding>(private val inflater: (LayoutInflater) -> VB) :
    AppCompatActivity(), OnNetChangerListener {

    protected val scopeProvider by lazy { AndroidLifecycleScopeProvider.from(this) }
    private var dialog: MessageDialog? = null

    lateinit var binding: VB

    //是否首页登录
    protected var isHome = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (AppStatusManger.instance.mAppStatus == AppStatus.STATUS_KILLED) {
            val intent = baseContext.packageManager
                .getLaunchIntentForPackage(baseContext.packageName)
            intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
            exitProcess(0)

            return
        }
        binding = inflater(layoutInflater)
        isHome = intent.getBooleanExtra("isHome", false)
        setContentView(binding.root)
        initView()
        setListener()
        AppManager.attach(this)
        NetChangerReceiver.addListener(this)

        LiveDataBus.get().with("recreate").observe(this) {
            window.setWindowAnimations(R.style.WindowAnimationFadeInOut)
            recreate()
        }

        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v: View, insets: WindowInsetsCompat ->
            val navInsets = insets.getInsets(WindowInsetsCompat.Type.navigationBars())
            v.setPadding(0, 0, 0, navInsets.bottom)
            insets
        }
    }

    /**
     * 初始化界面
     */
    abstract fun initView()

    abstract fun setListener()

    override fun onResume() {
        super.onResume()
        onDisconnect(NetUtil.isAvailable(this))
    }

    override fun onDestroy() {
        super.onDestroy()
        AppManager.detach(this)
        dismissDialog()
        dialog = null
        MLoadingDialog.clear()
        NetChangerReceiver.removeListener(this)
    }


    /**
     * 断网监听处理
     */
    override fun onDisconnect(isDisconnect: Boolean) {
        if (!isDisconnect)
            showNetDialog(R.string.toast_net_available)
        else dismissDialog()
    }


    /**
     * 显示Dialog
     */
    private fun showNetDialog(@StringRes message: Int) {
        showDialog(getString(message))
    }

    /**
     * 网络弹窗
     */
    private fun showDialog(message: String) {
        dialog = dialog ?: MessageDialog(this, positive = R.string.dialog_setting, clickListener = {
            NetUtil.openWirelessSettings(this)
        })
        dialog?.show(message)
    }

    /**
     * 隐藏Dialog
     */
    private fun dismissDialog() {
        dialog?.apply {
            if (isShowing) dismiss()
        }
    }

    fun isShowLoading(isShow: Boolean) {
        if (isShow) MLoadingDialog.showLoading(this) else MLoadingDialog.dismiss()
    }

    fun toastObserver(entity: ToastEntity) {
        if (entity.toast.isNotEmpty()) {
            toast(entity.toast)
            return
        }
        if (entity.toastId != 0) {
            toast(entity.toastId)
            return
        }
        isShowLoading(entity.isShowLoading)
    }

    override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
        // 兼容androidX在部分手机切换语言失败问题
        if (overrideConfiguration != null) {
            val uiMode: Int = overrideConfiguration.uiMode
            overrideConfiguration.setTo(baseContext.resources.configuration)
            overrideConfiguration.uiMode = uiMode
        }
        super.applyOverrideConfiguration(overrideConfiguration)
    }


    /**
     * 设置语言
     */
    override fun attachBaseContext(context: Context) {
        if (BuildConfigs.DefaultLanguage != "zh_CN")
            super.attachBaseContext(
                Language.attachBaseContext(
                    context,
                    BuildConfigs.DefaultLanguage
                )
            )
        else
            super.attachBaseContext(Language.attachBaseContext(context))
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isHome) {
                startHomeActivity()
                return false
            }

        }
        return super.onKeyDown(keyCode, event)
    }

    protected fun startHomeActivity() {
        zClass?.run {
            startActivity(Intent(this@BaseActivity, this))
            finish()
        }
    }
}